package com.seari.main;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sun.jvmstat.monitor.MonitorException;

import com.seari.bean.BaseTaskBean;
import com.seari.bean.LogBean;
import com.seari.service.LogService;
import com.seari.utils.ProcessUtil;
import com.seari.utils.SpringContextUtil;

public class TaskRunner implements Runnable {

	private Logger logger = LoggerFactory.getLogger(TaskRunner.class);
	private static final String CMD = "cmd /c start ";

	private BaseTaskBean task;

	public TaskRunner(BaseTaskBean task) {
		this.task = task;
	}

	@Override
	public synchronized void run() {
		try {
			if (task.getType().equals("JAR")) {
				String pid;
				pid = ProcessUtil.getProcessIdByName(task.getTaskName());
				if (pid != null && !"".equals(pid)) {
					Runtime.getRuntime().exec("taskkill /F /PID " + pid);
					logger.info("杀死进程:" + pid + " ...");
					TimeUnit.SECONDS.sleep(3);
					logger.info("重启项目 :" + task.getTaskName() + " ...");
					ProcessUtil.executeCommand(CMD + task.getScriptPath());
					insertLog(task);
				} else {
					logger.info("重启项目 :" + task.getTaskName() + " ...");
					ProcessUtil.executeCommand(CMD + task.getScriptPath());
					insertLog(task);

				}
			}else {
				Runtime.getRuntime().exec("taskkill /F /IM " + task.getTaskName() + ".exe");
				TimeUnit.SECONDS.sleep(2);
				ProcessUtil.executeCommand(CMD + task.getScriptPath());
			}
		} catch (MonitorException | URISyntaxException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void insertLog(BaseTaskBean task) {
		LogService logService = SpringContextUtil.getBean(LogService.class);
		LogBean log = new LogBean();
		log.setServiceName(task.getTaskName());
		log.setContent("重启 " + task.getTaskName() + " 服务");
		log.setState("start");
		try {
			logService.addLog(log);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
